<?
	// Setup Db
	require_once('dbController.php');
	require_once('glGlobals.php');

	$glDb = new dbController($DB_CONNECT);

	if(!isset($_REQUEST['gameid'])) {
		die();
	}
	
	$gid = $_REQUEST['gameid'];
	/*
	 roundtime
	 users
	 userturn
	 gamestats
	 imagequery
	 dropid
	 dropsrc
	 go
	 guess
	 word
	 */

	$SQL = "SELECT roundstarttime, userturn, action, data1, data2, go, round, word FROM roundstate WHERE gameid = $gid ORDER BY moveid DESC";
	$results = $glDb->getRow($SQL);
	$roundtime = $results[0];
	$userturn = $results[1];
	$action = $results[2];
	$data1 = $results[3];
	$data2 = $results[4];
	$go = $results[5];
	$round = $results[6];
	$query = '';
	$word = $results[7];
	
	$SQL = "SELECT username,team FROM gameusers WHERE gameid = $gid";
	$users = $glDb->query($SQL);
	$usertext = "<ul>";
	$currentuserteam = '';
	while($user = $users->fetchRow()) {
		$username = $user[0];
		$userteam = $user[1];
		if($userturn == $username) {
			$usertext .= "<li><font color=\"red\">$user[0] (Team $userteam)</font></li>";
			$currentuserteam = $userteam;
		} else {
			$usertext .= "<li>$user[0] (Team $userteam)</li>";
		}
	}
	
	$usertext .= '<ul>';

	$SQL = "SELECT rounds, pointsa, pointsb, gamename, roundlength FROM gamestate WHERE gameid = $gid";
	$results = $glDb->getRow($SQL);
	$rounds = $results[0];
	$pointsa = $results[1];
	$pointsb = $results[2];
	$gamename = $results[3];
	$roundlength = $results[4];
	$gamestats = "Game: $gamename<br />Round: $round/$rounds<br />Team A: $pointsa Points<br />Team B: $pointsb Points";

	$imagequery = '';
	$dropid = '';
	$dropsrc = '';
	
	$guesstext = '';
	$SQL = "SELECT data1 FROM roundstate WHERE gameid = $gid AND action like 'guess' ORDER BY moveid DESC";
	$guesses = $glDb->query($SQL);
	while($guess = $guesses->fetchRow()) {
		if($guess[0] != '') {
			$guesstext .= $guess[0] . "<br />";
		}
	}
	
	if($action == "query") {
		$query = $data1;
		$dropid = '';
		$dropsrc = '';
	} else if ($action == "drop") {
		$imagequery = '';
		$dropid = $data1;
		$dropsrc = $data2;
	}
	if($go == 1) {
		$roundtime = $roundlength - time() + $roundtime;
		if ($roundtime < 0) {
			// End the game by inserting a new row, ending the round
			$time = time();
			if($round < $rounds) {
				// Switch the team
				if($currentuserteam == 'A') {
					$currentuserteam = 'B';
				} else {
					$currentuserteam = 'A';
					$round++;
				}
				// Get a new user
				$SQL = "SELECT username FROM gameusers WHERE gameid = $gid AND team = '$currentuserteam'";
				$userturn = $glDb->getOne($SQL);
				$SQL = "INSERT INTO roundstate (gameid, round, roundstarttime, action, data1, data2, go, userturn) VALUES ($gid,$round,$time,'','','',0,'$userturn')";
				$glDb->query($SQL);

			} else {
				// End the game
			}
		}
	}
	else {
		$roundtime = $roundlength;
	}
	$results = "Round Time: $roundtime,,,$usertext,,,$userturn,,,$gamestats,,,$query,,,$dropid,,,$dropsrc,,,$go,,,$guesstext,,,$word";
	print $results;
?>
